package com.personal.website.lottery.web.controller;

import com.personal.website.lottery.web.model.Article;
import com.personal.website.lottery.web.model.Comment;
import com.personal.website.lottery.web.model.User;
import com.personal.website.lottery.web.service.ArticleService;
import com.personal.website.lottery.web.service.CommentService;
import com.personal.website.lottery.web.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 10171225 on 2016/2/18.
 */
@Controller
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private ArticleService articleService;
    @Resource
    private UserService userService;
    @Resource
    private CommentService commentService;

    private final Logger logger = LoggerFactory.getLogger(ArticleController.class);

    @RequestMapping("/create")
    @ResponseBody
    public String create(HttpSession session, HttpServletRequest request) {
        String userName = null;
        String title = null;

        try {
            String content = URLDecoder.decode(request.getParameter("content"), "UTF-8");
            String tag = URLDecoder.decode(request.getParameter("tag"), "UTF-8");
            title = URLDecoder.decode(request.getParameter("title"), "UTF-8");

            int userId = (Integer) session.getAttribute("userId");
            userName = (String) session.getAttribute("userName");
            Article article = new Article();
            article.setTitle(title);
            article.setContent(content);
            article.setIsReviewed((byte)0);
            article.setIsTop((byte)0);
            article.setSubmitTime(new Date());
            article.setTag(tag);
            article.setCommnetTimes(0);
            article.setWatchTimes(0);
            article.setUserId(userId);
            article.setUserName(userName);
            this.articleService.insertArticle(article);
        } catch (Exception e) {
            logger.error(String.format("用户‘%s’发表主题为'%s'的文章失败！", userName, title),e);
            return "文章发表失败！";
        }
        logger.info(String.format("用户‘%s’发表主题为'%s'的文章成功！", userName, title));
        return "文章发表成功，请等待审核！";
    }

    @RequestMapping("/show")
    public String show(HttpServletRequest request,Model model) {
        int articleId = -1;
        try {
            articleId = Integer.parseInt(request.getParameter("articleId"));
            Article article = this.articleService.selectArticleById(articleId);
            User user = this.userService.getUserById(article.getUserId());
            List<Comment> commentLst = this.commentService.getCommentsByArcicleId(articleId);

            article.setWatchTimes(article.getWatchTimes() + 1);

            model.addAttribute("article",article);
            model.addAttribute("user",user);
            model.addAttribute("commentLst",commentLst);

            if(this.articleService.updateArticle(article)) {
                logger.debug(String.format("文章'%d'查看次数增加一次！", articleId));
            } else {
                logger.error(String.format("文章'%d'查看次数增加一次失败！", articleId));
            }
        } catch (Exception e) {
            logger.error(String.format("文章‘%d’显示失败！", articleId),e);
            return "redirect:/indexContent";
        }

        return "showArticle";
    }

    @RequestMapping("/editShow")
    public String editShow(HttpServletRequest request,HttpSession session,Model model) {
        int userId = -1;
        Article article = null;
        int articleId = -1;
        try {
            articleId = Integer.parseInt(request.getParameter("articleId"));
            userId = (Integer) session.getAttribute("userId");
            article = this.articleService.selectArticleById(articleId);
        } catch (Exception e) {
            logger.error(String.format("用户'%d'编辑显示文章'%d'失败！", userId, articleId), e);
            model.addAttribute("tab","issuedArticles");
            return "personalHomePage";
        }
        if(article != null && !article.getUserId().equals(userId)){
            return "redirect:/indexContent";
        } else if (article == null) {
            return "redirect:/indexContent";
        }
        model.addAttribute("article",article);
        return "editArticle";
    }

    @RequestMapping("/editSubmit")
    @ResponseBody
    public String editSubmit(HttpServletRequest request,HttpSession session) {
        int userId = -1;
        String title = null;
        try {
            String articleId = URLDecoder.decode(request.getParameter("articleId"),"UTF-8");
            title = URLDecoder.decode(request.getParameter("title"),"UTF-8");

            String content = URLDecoder.decode(request.getParameter("content"),"UTF-8");
            String tag = URLDecoder.decode(request.getParameter("tag"),"UTF-8");

            Article article = this.articleService.selectArticleById(Integer.parseInt(articleId));
            userId = (Integer) session.getAttribute("userId");
            if(article.getUserId() != userId){
                logger.error(String.format("用户‘%d’不是文章'%s'的创建人，没有编辑权限！", userId, title));
                return "您不是该文章的创建人，您没有权限编辑！";
            }
            article.setContent(content);
            article.setIsReviewed((byte) 0);
            article.setTag(tag);
            article.setTitle(title);
            if(this.articleService.updateArticle(article)) {
                logger.info(String.format("用户‘%d’编辑主题为'%s'的文章，编辑成功！", userId, title));
                return "编辑成功，请等待重新审核！";
            } else {
                logger.error(String.format("用户‘%d’编辑主题为'%s'的文章，提交失败！", userId, title));
                return "编辑失败！";
            }

        } catch (Exception e) {
            logger.error(String.format("用户‘%d’编辑主题为'%s'的文章，提交失败！", userId, title),e);
            return "编辑失败！";
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(HttpServletRequest request,HttpSession session) {
        int userId = -1;
        int articleId = -1;
        try {
            articleId = Integer.parseInt(request.getParameter("articleId"));
            Article article = this.articleService.selectArticleById(articleId);
            userId = (Integer) session.getAttribute("userId");
            if(article == null){
                logger.error(String.format("用户‘%d’删除文章'%d'时，文章不存在！", userId, articleId));
                return "不存在该文章！";
            }
            if(article.getUserId() != userId){
                logger.error(String.format("用户‘%d’不是文章'%d'的创建人，没有删除权限！", userId, articleId));
                return "你不是该文章的创建人，没有权限删除！";
            }
            if(this.articleService.deleteArticle(articleId)) {
                logger.info(String.format("用户‘%d’删除文章'%d'，删除成功！", userId, articleId));
                return "删除成功！";
            } else {
                logger.error(String.format("用户‘%d’删除文章'%d'，删除失败！", userId, articleId));
                return "删除失败！";
            }
        } catch (Exception e) {
            logger.error(String.format("用户‘%d’不是文章'%d'的创建人，没有删除权限！", userId, articleId), e);
            return "删除失败！";
        }
    }

    @RequestMapping("/comment")
    @ResponseBody
    public String comment(HttpServletRequest request,HttpSession session) {
        int userId = -1;
        int articleId = -1;
        try {
            articleId = Integer.parseInt(request.getParameter("articleId"));
            userId = (Integer) session.getAttribute("userId");
            String userName = (String) session.getAttribute("userName");
            String content = URLDecoder.decode(request.getParameter("commentContent"),"UTF-8");
            Comment comment = new Comment();
            comment.setArticleId(articleId);
            comment.setUserId(userId);
            comment.setUserName(userName);
            comment.setContent(content);
            comment.setSubmitTime(new Date());
            this.commentService.insertComment(comment);

            Article article = this.articleService.selectArticleById(articleId);
            article.setCommnetTimes(article.getCommnetTimes() + 1);
            if(this.articleService.updateArticle(article)) {
                logger.debug(String.format("文章'%d'评论次数增加一次!", articleId));
            } else {
                logger.error(String.format("文章'%d'评论次数增加一次失败!", articleId));
            }
        } catch (Exception e) {
            logger.error(String.format("用户'%d'评论文章'%d'时，评论失败！", userId, articleId),e);
            return "评论失败！";
        }
        logger.info(String.format("用户'%d'评论文章'%d'时，评论成功！", userId, articleId));
        return "评论成功！";

    }

    @RequestMapping("/search")
    public String search(HttpServletRequest request, Model model) {
        String text = null;
        try {
            text = request.getParameter("text");
            text = URLDecoder.decode(text, "UTF-8");
            model.addAttribute("searchInput", text);
            model.addAttribute("articles",this.articleService.getArticles("%" + text + "%", 30));
        } catch (Exception e) {
            logger.error(String.format("搜索主题为'%s'的文章时失败！", text), e);
        }
        return "articles";
    }
}
